package com.yanhui.utils.file.qiniu;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.yanhui.modal.file.QiNiuConfig;
import com.yanhui.modal.file.TokenGenerator;
import com.yanhui.modal.file.UploadResult;

import java.io.*;

/**
 * @Description 七牛文件上传/删除
 * @Author yanhui
 * @Date 2018-11-30 14:01
 */
public class _qiniuFileUtils {

    public UploadResult uploadFile(File file, String fileName, String prefix) throws Exception {
        if (file == null) {
            throw new Exception("文件不能为空") ;
        }
        return this.uploadFile(new FileInputStream(file), fileName, prefix) ;
    }

    public UploadResult uploadFile(InputStream file, String fileName, String prefix) throws Exception{
        String token = TokenGenerator.getUpToken() ;
        UploadManager uploadManager = new UploadManager();
        fileName = prefix + fileName ;
        Response res = uploadManager.put(input2byte(file), fileName, token);
        UploadResult ret = res.jsonToObject(UploadResult.class);
        ret.setPath(fileName);
        return ret ;
    }

    public static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        return swapStream.toByteArray();
    }

    public void deleteFile(String fileName) throws Exception {
        //设置需要操作的账号的AK和SK
//	    String ACCESS_KEY = "Access_Key";
//	    String SECRET_KEY = "Secret_Key";
        Auth auth = Auth.create(QiNiuConfig.AK.getCode(),QiNiuConfig.SK.getCode());
        //实例化一个BucketManager对象
        BucketManager bucketManager = new BucketManager(auth);
        //要测试的空间和key，并且这个key在你空间中存在
        //String bucket = "yanhui";
        String bucket = QiNiuConfig.BUCKET.getCode();
        String key = fileName;
        try {
            //调用delete方法移动文件
            bucketManager.delete(bucket, key);
            //System.out.println("删除文件成功！");
        } catch (QiniuException e) {
            //捕获异常信息
            Response r = e.response;
            System.out.println(r.toString());
        }
    }
}
